import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author: fei.wu
 * @Email: fei.wu@rograndec.com
 * @CreateDate: 2019/1/2
 * @Version: 1.0
 */
public class SemaphoreThread {

    int a = 0;

    class Piggy {
        private volatile int account;

        private int in;

        private int save(int in) {
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account = account + in;
            return account;
        }

    }

    class NewThread implements Runnable {

        private Piggy piggy;

        private Semaphore semaphore;

        @Override
        public void run() {
            int b = a++;
            if (semaphore.availablePermits() > 0) {
                System.out.println(b + ": 可执行 ^-^");
            } else {
                System.out.println(b + ": 不可执行 -_-");
            }

            try {
                semaphore.acquire();
                System.out.println(b + " > 开始");
                int save = piggy.save(10);
                System.out.println(b + " > 已经存入 10 元 , 余额: " + save);
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

        public NewThread(Piggy piggy, Semaphore semaphore) {
            this.piggy = piggy;
            this.semaphore = semaphore;
        }
    }

    private void start() throws InterruptedException {
        int permits = 5;
        long l = System.currentTimeMillis();
        Piggy piggy = new Piggy();
        Semaphore semaphore = new Semaphore(permits);
        NewThread newThread = new NewThread(piggy, semaphore);

        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            pool.submit(newThread);
        }
        pool.shutdown();
        semaphore.acquireUninterruptibly(permits);
        System.out.println("型号量空余"+permits+",线程执行完成.");
        semaphore.release(permits);
        pool.awaitTermination(20, TimeUnit.SECONDS);
        long l1 = System.currentTimeMillis();
        System.out.println("耗时 : " + (l1 - l));
    }

    public static void main(String[] args) throws InterruptedException {

        SemaphoreThread thread = new SemaphoreThread();
        thread.start();

    }
}
